<template>
    <van-form ref="phoneCaptchaForm" @submit="values => $emit('submit', values)">
        <phone-field v-model="phoneValue"/>
        <van-field class="login-token-field" v-model="captchaToken" name="captchaToken"/>
        <sms-captcha-field v-model="captchaCode" :sending="captchaSending" :time="captchaSendingTime"
                           @finish="captchaSending = false" @send="handleSendCaptcha"/>
        <van-button class="login-button" type="primary" native-type="submit" :loading="loading" block>登录</van-button>
    </van-form>
</template>

<script>
  import { Button, Field, Form, Toast } from "vant"
  import PhoneField from "@/views/user/PhoneField"
  import SmsCaptchaField from "@/views/user/SmsCaptchaField"
  import { captcha, message } from "@mall/api-services"

  export default {
    name: "PhoneCaptchaForm",
    components: {
      SmsCaptchaField,
      PhoneField,
      [Button.name]: Button,
      [Form.name]: Form,
      [Field.name]: Field,
    },
    model: {
      prop: "phone",
      event: "change-mobile",
    },
    props: {
      loading: Boolean,
      mobile: {
        type: String,
        default: "",
      },
    },
    watch: {
      phone(phone) {
        this.phoneValue = phone
      },
    },
    data() {
      return {
        phoneValue: "",
        captchaCode: "",
        captchaLoading: false,
        captchaSendingTime: 60000,
        captchaSending: false,
        captchaToken: "",
        registering: false,
      }
    },
    created() {
      this.phoneValue = this.phone
    },
    methods: {
      handleSendCaptcha() {
        this.$refs.phoneCaptchaForm.validate("phone")
          .then(() => {
            const { phoneValue: phone } = this
            const newCaptcha = new captcha.Captcha()
            newCaptcha.type = captcha.CaptchaType.Sms
            newCaptcha.parameters = {
              country_code: "86",
              phone,
            }
            this.captchaLoading = true
            captcha.CaptchaServiceV1.generateCaptcha(newCaptcha)
              .then(aCaptcha => {
                this.captchaSendingTime = aCaptcha.intervals
                this.captchaSending = true
                this.captchaToken = aCaptcha.token
              })
              .catch(({ response }) => Toast(message.getResponseMessage(response)))
              .finally(() => this.captchaLoading = false)
          })
      },
    },

  }
</script>

<style scoped>
    .login-token-field {
        display: none;
    }

    .login-button {
        margin-top: 30px;
    }
</style>
